<!--
 * @Author: panda
 * @Date: 2022-05-18 10:04
 * @Description: Markdown 组件，copy别人的
-->
<template>
  <div ref="wrapRef"></div>
</template>
<script lang="ts">
import type {Ref} from 'vue'
import {
  defineComponent,
  nextTick,
  onBeforeUnmount,
  onDeactivated,
  ref,
  unref,
  watch
} from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import {onMountedOrActivated} from '@/hooks/core/onMountedOrActivated'
import {cosApi} from "@/api/cos";
import {v4 as uuidv4} from "uuid";
import {CosAuth} from "@/utils/cosAuth";

export default defineComponent({
  inheritAttrs: false,
  props: {
    height: {type: Number, default: 600},
    width: {type: String, default: '100%'},
    value: {type: String, default: ''}
  },
  emits: ['change', 'get', 'update:value'],
  setup(props, {attrs, emit}) {
    const wrapRef = ref<ElRef>(null)
    const vditorRef = ref(null) as Ref<Nullable<Vditor>>
    const initedRef = ref(false)
    const valueRef = ref(props.value || '')
    const imgUrl = ref('')
    watch(
      () => props.value,
      (v) => {
        if (v !== valueRef.value) {
          instance.getVditor()?.setValue(v)
        }
        valueRef.value = v
      }
    )

    function init() {
      const wrapEl = unref(wrapRef) as HTMLElement
      if (!wrapEl) return
      const bindValue = {...attrs, ...props}
      const insEditor = new Vditor(wrapEl, {
        // theme: getDarkMode.value === 'dark' ? 'dark' : 'classic',
        theme: 'classic',
        // lang: unref(getCurrentLang),
        lang: 'zh_CN',
        mode: 'sv',
        fullscreen: {
          index: 520
        },
        preview: {
          actions: []
        },
        input: (v) => {
          valueRef.value = v
          emit('update:value', v)
          emit('change', v)
        },
        after: () => {
          nextTick(() => {
            insEditor.setValue(valueRef.value)
            vditorRef.value = insEditor
            initedRef.value = true
            emit('get', instance)
          })
        },
        blur: () => {
          unref(vditorRef)?.setValue(props.value);
        },

        //  上传图片
        upload: {
          url: 'http://panda-1308597681.cos.ap-guangzhou.myqcloud.com/',
          accept: 'image/jpg, image/jpeg, image/png',//规定上传的图片格式，
          linkToImgUrl: imgUrl.value,
          linkToImgFormat(responseText: string): string {
            console.log(this.extraData)
            let result = JSON.parse(responseText)
            if (result.status === true) {
              return '{msg:"",code:0,data:{{"originalURL":"' + result.data.originalUrl + '","url":"' + result.data.url + '"}}'
            } else {
              return '{msg:"' + result.msg + '",code:-1,data:{{"originalURL":"","url":""}}'
            }
          },
          file(files: File[]): File[] | Promise<File[]> {
            return cosApi.getCredential({}).then(res => {
              const {data} = res.data
              const cosAuth = CosAuth({
                SecretId: data.credentials.tmpSecretId,
                SecretKey: data.credentials.tmpSecretKey,
                Method: "POST",
                Pathname: "/",
              });
              const time = new Date().getTime();
              const uuid = uuidv4()
              const results = /\.\w+$/.exec(files[0].name)
              const extname = results ? results[0] : ''
              // extra['key'] = time + '-' + uuid + extname
              // extra['Signature'] = cosAuth as string
              // extra['x-cos-security-token'] = data.credentials.sessionToken
              // extra['success_action_status'] = 200 + ''
              // extra['success_action_redirect'] = '/'
              this.extraData!['key'] = time + '-' + uuid + extname
              this.extraData!['Signature'] = cosAuth as string
              this.extraData!['x-cos-security-token'] = data.credentials.sessionToken
              this.extraData!['success_action_status'] = 200 + ''
              this.extraData!['success_action_redirect'] = '/'
              return Promise.resolve(files)
            }).catch(
              err => {
                return Promise.reject(err)
              }
            )
          },
          format(files: File[], responseText: string): string {
            let data = JSON.parse(responseText)
            let filName = data.result.cover_files
            //上传图片请求状态
            if (data.ret_code == 200) {
              let lastTipNum = filName.substr(filName.lastIndexOf('/', filName.lastIndexOf('/') - 1) + 1);
              let index = lastTipNum.lastIndexOf("\/");
              console.log(index)
              // self.imgNameStr = decodeURI(lastTipNum.substring(index + 1, lastTipNum.length));
              //
              // let responseData = self.gb.imgPath(data.result.cover_files)
              // let succ = {}
              // succ[self.imgNameStr] = responseData
              // //图片回显
              // return JSON.stringify({
              //   msg,
              //   code,
              //   data:{
              //     errFiles: [],
              //     succMap: succ
              //     // succMap: {
              //     //   'default.png': `${responseData}`
              //     // }
              //   }
              // })
            } else {
              console.log("失败")
            }
            return responseText
          },
          success(editor: HTMLPreElement, msg: string) {
            console.log(editor)
            console.log(msg)
          },
          error(msg: string) {
            console.log(this)
            console.log(msg)
          },
          // handler(files: File[]): Promise<any> {
          //   console.log(123123123)
          //   return cosApi.getCredential({}).then(res => {
          //     const {data} = res.data
          //     url.value = 'https://panda-1308597681.cos.ap-guangzhou.myqcloud.com/image'
          //     extra = data
          //     console.log(extra)
          //     return Promise.resolve(files)
          //   }).catch(
          //     err => {
          //       return Promise.reject(err)
          //     }
          //   )
          // },
          extraData: {},

        },
        ...bindValue,
        cache: {
          enable: false
        }
      })
    }

    const instance = {
      getVditor: (): Vditor => vditorRef.value!
    }

    function destroy() {
      const vditorInstance = unref(vditorRef)
      if (!vditorInstance) return
      try {
        vditorInstance?.destroy?.()
      } catch (error) {
        console.log(error)
      }
      vditorRef.value = null
      initedRef.value = false
    }

    onMountedOrActivated(init)
    onBeforeUnmount(destroy)
    onDeactivated(destroy)
    return {
      wrapRef,
      ...instance,
    }
  }
})
</script>
